--- 模块功能：播放拨号音功能
-- @author miuser
-- @module elderphone.system
-- @license MIT
-- @copyright miuser
-- @release 2020-05-15


require"common"
require"audio"
module(...,package.seeall)

--网络状态 未联网、已联网
local net="未联网"
--状态机 摘机、扣机、通话、拨号检测、响铃
local status="扣机"
local laststatus=""

--初始化
local function netready()
    if (net=="未联网") then
        net="已联网"
    end
    if status=="摘机" then
        status="拨号检测"
        sys.publish("PLAY_450Hz")
    end
end
sys.subscribe("NET_STATE_REGISTERED", netready)


--接听来电
local function incoming()
    if (status=="扣机") then
        status="响铃"
        sys.publish("ALARM_ON")
    else
        status="通话"
        sys.publish("ANSWER")
    end
end
sys.subscribe("CALL_INCOMING",incoming)

--对方主动断线
local function disconnected()
    if (status=="响铃") then
        status="扣机"
    else
        audio.play(0,"TTS","通话已结束",4)
    end
end
sys.subscribe("CALL_DISCONNECTED",disconnected)


--摘机
local function offhook()
    sys.publish("ALARM_OFF")
    if (status=="响铃") then
        status="通话"
        sys.publish("ANSWER")
    elseif (net=="已联网") then
        status="拨号检测"
        sys.publish("PLAY_450Hz")
    else
        status="摘机"
        audio.play(0,"TTS","正在初始化，请听到拨号音后再开始拨号",4)
    end
end
sys.subscribe("OFF_HOOK",offhook)

local function calling(num)
    sys.publish("ALARM_OFF")
    sys.publish("CALL",num)
    status="通话"
end
sys.subscribe("DIALOUT",calling)


local function over()
    if (status=="通话") then
        log.info("system","sending message over")
        sys.publish("OVER")
    end
    status="扣机"
    sys.publish("STOP_450Hz")
end
sys.subscribe("ON_HOOK",over)

--正在拨号
local function dialing()
    sys.publish("STOP_450Hz")
end
sys.subscribe("PLATE_MOVING",dialing)

local function forceover()
    sys.publish("ALARM_OFF")
end
sys.subscribe("CALL_DISCONNECTED",forceover)

local function statusdetect()
    if laststatus~=status then
        sys.publish("UARTOUT","["..laststatus.."]->["..status.."]")
        laststatus=status

    end
end
sys.timerLoopStart(statusdetect, 10)